/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csvreader.service;

import csvreader.model.Contact;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.Scanner;

/**
 *
 * @author 11.6711
 */
public class DaoContact {

    private Contact contact;
    private Set<Contact> setContact;
    private File f;

    public DaoContact() {
    }

    public DaoContact(File f) throws FileNotFoundException, IOException, ClassNotFoundException {
        setContact = new HashSet();
        this.f = f;
        readFile();
    }

    private void readFile() throws FileNotFoundException, IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(f);
        boolean eof = false;
        try {
            ObjectInputStream ois = new ObjectInputStream(fis);
            while (!eof) {
                setContact.add((Contact) ois.readObject());
            }
        } catch (EOFException e) {
            eof = true;
        }
    }

    public Set<Contact> getSetContact() {
        return setContact;
    }

    public void addData(Contact co) throws IOException, Exception {
        if (setContact.contains(co)) {
            throw new Exception("Kontak sudah ada");
        } else {
            setContact.add(co);
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            for (Contact c : setContact) {
                oos.writeObject(c);
            }
            fos.close();
            oos.close();
        }
    }

    public File getFile() {
        return f;
    }

    public void deleteContact(Contact co) throws FileNotFoundException, IOException {
        setContact.remove(co);
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        for (Contact c : setContact) {
            oos.writeObject(c);
        }
        fos.close();
        oos.close();
    }

    public void cariContact(String nama) throws Exception {
        if (setContact.contains(nama)) {
        } else {
            throw new Exception("Contact tidak ditemukan");
        }
    }
}
